<template>
    <div class="label-result-bg">
        <div class="title-font">{{ _image_url }} 属性</div>
        <div class="img-property-panel">
            <div class="img-property">基础信息： {{ _image_info }}</div>
            <div class="img-property">
                <span>标注状态： {{ _image_status }}</span>
                <span :class="_class_status">{{ _local_status }}</span>
            </div>
            <div class="img-property">创建时间： {{ _create_time }}</div>
            <div class="img-property">更新时间： {{ _update_time }}</div>
        </div>
        <el-divider />
        <div class="title-font">标注结果</div>
        <div class="label-list">
            <el-table size="small" :data="_label_list" style="width: 100%; height: 100%"
                :header-cell-style="headerCellStyle" :cell-style="cellStyle" table-layout="auto">
                <el-table-column prop="text" label="标注结果" min-width="130">
                    <template #default="scope">
                        <div class="caption-cell" @click="handleCell(scope)" @dblclick="handleDbCell(scope)">
                            {{ scope.row.text }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="60" align="center">
                    <template #default="scope">
                        <el-button plain :icon="Close" size="small" circle type="danger"
                            @click="handleDelete(scope.$index, scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
    <!-- edit label dialog -->
    <el-dialog v-model="_dialogFormVisible" title="编辑标注" align-center width="450px" :before-close="handleBeforeClose">
        <el-form ref="editForm" :model="_form" label-position="right" :rules="_rules" @submit.native.prevent>
            <el-form-item label="标注内容" prop="caption" :label-width="_formLabelWidth">
                <el-input v-model="_form.caption" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入标注内容" class="form-input-caption" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="onEditLabel"> 确定 </el-button>
                <el-button @click="closeEditDialog()">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, getCurrentInstance, inject } from 'vue';
import { Close } from '@element-plus/icons-vue';
const emit = defineEmits(['changeLabelMode', 'deleteLabel', 'selectLabel']);
const { proxy } = getCurrentInstance();
let vueApp = inject('vueApp');

// 图片相关的ui控制变量
const _image_url = ref('');
const _image_info = ref('');
const _image_status = ref('');
const _local_status = ref('');
const _class_status = ref('');
const _create_time = ref('');
const _update_time = ref('');

// 标注结果相关的ui控制变量
let _label_result = null;
const _label_list = ref([]);
const _selected_label_id = ref(-1);

// 编辑标注结果控制变量
let _dialogFormVisible = ref(false);
let _formLabelWidth = '100px';
let _form = reactive({
    id: -1,
    caption: ''
});

let _rules = reactive({
    caption: [
        {
            required: true,
            message: '请输入标注内容',
            trigger: 'blur'
        }
    ]
});
let _dlg_mode = ref('rect');
let _dlg_callback = null;

function showEditDialog(mode, label_id, callback) {
    // console.log('showEditDialog mode = ', mode, ', label_id = ', label_id);
    _dlg_mode.value = mode;
    if (label_id !== null || label_id !== undefined) {
        _form.id = label_id;
        _form.caption = _label_list.value.find(item => item.id === label_id)?.text || '';
    }
    _dlg_callback = callback;
    _dialogFormVisible.value = true;
    vueApp.monitorKeyEvent(false);
}

function closeEditDialog() {
    _dialogFormVisible.value = false;
    vueApp.monitorKeyEvent(true);
}

function handleBeforeClose(done) {
    vueApp.monitorKeyEvent(true);
    done();
}

async function onEditLabel() {
    let editForm = proxy.$refs.editForm;
    await editForm.validate((valid, fields) => {
        if (valid) {
            // 获取dialog输入的信息
            let label = {
                id: _form.id,
                caption: _form.caption
            };

            // 调用回调函数，处理更新或者新增label
            if (_dlg_callback) {
                _dlg_callback(label);
            }

            // 关闭对话框
            closeEditDialog();
        } else {
            console.log('error submit!', fields);
        }
    });
}

// 对于标注结果的处理函数
function headerCellStyle({ row, index }) {
    return {
        color: '#fff',
        'background-color': '#373133'
    };
}

function cellStyle({ row, column, rowIndex, columnIndex }) {
    // console.log(row, column, rowIndex, columnIndex);
    let style = {};

    if (columnIndex == 0) {
        style['color'] = '#000';
        style['background-color'] = 'rgb(240, 240, 240)';
    }

    // console.log(`row.id = ${row.id}, _selected_label_id = ${_selected_label_id.value}`);
    if (row.id == _selected_label_id.value) {
        style['font-weight'] = 'bold';
        if (columnIndex == 0) {
            style['color'] = '#fff';
            style['background-color'] = 'rgb(196, 74, 74)';
        } else {
            style['background-color'] = 'rgb(233, 187, 187)';
        }
    }

    return style;
}

// =================================================================
// 对应的数据处理逻辑
function loadData(data, proxy) {
    // console.log('LabelResult.vue loadData = ', data);
    _image_url.value = data.name;
    _image_status.value = data.status;
    _local_status.value = data.label_result.saved ? '（已保存）' : '（未保存）';
    _class_status.value = data.label_result.saved ? 'status-saved' : 'status-unsaved';

    _create_time.value = data.create_time.replace('T', ' ');
    _update_time.value = data.update_time.replace('T', ' ');
    _image_info.value = '';

    // 绑定vue3组件到label_result中
    data.label_result.bindLabelPanel(proxy);
    _label_result = data.label_result;
}

function handleCell(event) {
    // console.log('handleCell event = ', event);
    let data = _label_list.value[event.$index];
    selectLabel(data.id);
    emit('selectLabel', data.id);
}

function handleDbCell(event) {
    // console.log('handleDbCell event = ', event);
    let label = _label_result.labels[event.row.id];
    const keysOfInterest = ['ignore', 'iscrowd', 'truncated', 'occluded', 'difficult'];
    _form.id = label.id;
    _form.category = label.data.category;
    _form.properties = keysOfInterest.filter((key) => label.data[key] === 1);
    _form.segmentation = label.data.segmentation.map((segment, index) => ({
        seg_index: index,
        seg_coords: segment
    }));

    // 设置正在编辑的label_id
    _label_result.editing_label_id = label.id;
    showEditDialog('edit', label.id, (form) => {
        _label_result.updateLabel(form);
        updateLabel(label);
        emit('selectLabel', label.id);
    });
    handleCell(event);
}

function handleDelete(index, row) {
    // console.log(index, row);
    ElMessageBox.confirm(`确认删除“${row.text}”？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            deleteLabel(row.id);
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除！'
            });
        });
}

function updateImageInfo(info) {
    // console.log('LabelResult.vue updateImageInfo info = ', info);
    _image_info.value = info;
}

function loadLabels(labels) {
    // console.log('LabelResult.vue labels = ', labels);
    _label_list.value = [];
    _selected_label_id.value = -1;
    for (let i = 0; i < labels.length; i++) {
        let label = labels[i];
        if (!label) continue;
        let label_text = {
            id: label.id,
            text: label.data.caption.trim()
        };
        _label_list.value.push(label_text);
    }
}

function addLabel(data) {
    // console.log('LabelResult.vue addLabel data = ', data);
    // _label_data.label_result.addLabel(data);
    let label_text = {
        id: data.id,
        text: data && data.category.trim() ? data.category : '双击编辑'
    };
    _label_list.value.push(label_text);

    // update js object data
    _local_status.value = '（未保存）';
    _class_status.value = 'status-unsaved';
}

function updateLabel(update_info) {
    // console.log('LabelResult.vue::updateLabel update_info = ', update_info);
    const index = _label_list.value.findIndex((data) => data.id === update_info.id);
    if (index !== -1) {
        _label_list.value[index].text = update_info.data.caption.trim();
        _local_status.value = '（未保存）';
        _class_status.value = 'status-unsaved';
    }
}

function updateStatus() {
    _local_status.value = '（未保存）';
    _class_status.value = 'status-unsaved';
}

function deleteLabel(label_id, emitEvent = true) {
    // console.log('LabelResult.vue deleteLabel label_id = ', label_id);
    const index = _label_list.value.findIndex((data) => data.id === label_id);
    if (index !== -1) {
        _label_list.value.splice(index, 1);
        _local_status.value = '（未保存）';
        _class_status.value = 'status-unsaved';
    }

    if (emitEvent) {
        emit('deleteLabel', label_id);
    }
}

function selectLabel(label_id) {
    _selected_label_id.value = label_id;
}

function clearLabels() {
    // 清空当前视图的数据
    _label_list.value = [];
    _selected_label_id.value = -1;

    // clear js object data
    // _label_data.label_result.clearLabels();

    _local_status.value = '（未保存）';
    _class_status.value = 'status-unsaved';
}

onMounted(() => { });

defineExpose({
    loadData,
    updateImageInfo,
    loadLabels,
    addLabel,
    updateLabel,
    deleteLabel,
    selectLabel,
    clearLabels,
    showEditDialog,
    updateStatus
});
</script>

<style scoped>
.label-result-bg {
    background-color: rgb(69, 65, 65);
    width: 100%;
    height: 100%;
}

.img-property-panel {
    text-align: left;
    padding-left: 10px;
    padding-bottom: 5px;
}

.img-property-center {
    font-size: 14px;
    font-weight: 600;
    padding: 1px;
    color: rgb(135, 174, 222);
}

.img-property {
    font-size: 12px;
    padding: 3px;
    color: rgb(196, 197, 197);
}

.el-divider {
    margin: 10px 0 5px 0;
}

.title-font {
    margin: 8px;
    font-size: 12px;
    font-weight: bold;
    color: rgb(230, 230, 230);
    text-align: center;
}

.label-list {
    padding: 4px;
    /* height: 270px; */
    height: calc(100% - 184px);
    overflow-y: auto;
}

.status-saved {
    color: rgb(126, 196, 126);
}

.status-unsaved {
    color: rgb(224, 129, 129);
}

form-line {
    display: flex;
}

.form-input-category {
    width: 260px;
}

.form-btn-seg {
    margin-left: 2px;
}

.btn-add-seg {
    width: 100%;
    margin: 5px 5px 2px 5px;
}

.caption-cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 160px;
    display: block;
}
</style>
